package com.qcby.controller;


import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.qcby.Constants;
import com.qcby.model.resp.RespEntity;
import com.qcby.util.AliyunOssClientUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    /**
     * 图片上传的具体方法
     *
     * @throws IOException
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public RespEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            // 文件为空的情况，返回错误提示页面或者相应的JSON数据（如果是前后端分离项目）
            return RespEntity.errorNoData(Constants.FLAG_400, "文件为空！");
        }
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        logger.debug("上传的文件名为：" + originalFilename);
        // 获取文件后缀名
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成唯一的文件名，避免文件名冲突，可以使用UUID等方式
        String newFileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;


        // 将MultipartFile转换为File对象（也可以使用其他方式上传，比如直接使用流的方式）
        File tempFile = File.createTempFile("temp", fileExtension);
        file.transferTo(tempFile);
        String path = "pic/" + newFileName;
        AliyunOssClientUtils.uploadObject(tempFile, path);

        // 临时文件用完就删除
        tempFile.delete();
        return RespEntity.successCustomize(Constants.FLAG_200, "上传文件到oss成功！", path);
    }


    @RequestMapping("/uploadFileMp3")
    public void uploadFileMp3(HttpServletResponse response, MultipartFile mp3file, String fileType, String lastMp3, String update) throws IOException {

        // 后续现有代码逻辑
// 1.获取前端传递过来的所有有关于文件上传的参数
// MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request;

        //2.获取存储文件的相关内容
//        Map<String,MultipartFile> fileMap=mr.getFileMap();

        //3.获取文件
//        MultipartFile file=fileMap.get("picfile");

        //4.获取该文件的字节数组 方便上传
        byte[] bytes = mp3file.getBytes();

        //5.获取文件名称
        String originalFilename = mp3file.getOriginalFilename();
        //vhjbh.jpg
        //6.获取文件名的后缀 产生新的名字  .jpg(.exe)
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //7.定义一个新的名字  abscjsdc.jpg
        String fileName = UUID.randomUUID().toString();
        fileName = fileName + suffix;

        //8.上传  获取文件的上传位置  图片服务器的位置  http://localhost:8085  /pic/05.jpg
        String filePath = "http://localhost:8088";
        System.out.println(fileName);
        //绝对路径 http://localhost:8085/pic/05.jpg
        String realPath = filePath + "/" + fileType + "/" + fileName;
        //相对路径 /pic/05.jpg
        String relativePath = "/" + fileType + "/" + fileName;
        System.out.println(relativePath);
        //9.jersy客户端进行上传
        Client client = Client.create();

        //判断
        if (update.equals("false")) {
            if (lastMp3 != null && !"".equals(lastMp3)) {
                WebResource resource = client.resource(lastMp3);
                resource.delete();
            }
        }
        //10.获取web资源
        WebResource resource1 = client.resource(realPath);
        //11.上传
        resource1.put(bytes);
        //返回前端进行页面渲染
        JSONObject jo = new JSONObject();
        jo.put("realPath", realPath);
        jo.put("relativePath", relativePath);
        //响应对象的原始方式返回
        response.getWriter().write(jo.toString());

    }

    @RequestMapping("/deleteFile")
    public void deleteFile(String filePath, HttpServletResponse response) throws IOException {
        Client client = Client.create();
        WebResource resource = client.resource(filePath);
        resource.delete();
        //返回响应
        response.getWriter().write("File deleted successfully");
    }


}